package com.atguigu.srb.core.service.impl;

import com.alibaba.excel.EasyExcel;
import com.atguigu.srb.common.exception.BusinessException;
import com.atguigu.srb.common.result.ResponseEnum;
import com.atguigu.srb.core.listener.ExcelDictDTOListener;
import com.atguigu.srb.core.mapper.DictMapper;
import com.atguigu.srb.core.pojo.dto.ExcelDictDTO;
import com.atguigu.srb.core.pojo.entity.Dict;
import com.atguigu.srb.core.service.DictService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 数据字典 服务实现类
 * </p>
 *
 * @author javaCode
 * @since 2025-07-19
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {

    private final RedisTemplate<String, Object> redisTemplate;

    /**
     * Excel批量导入数据字典
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void importData(InputStream inputStream) {
        log.info("开始执行数据字典Excel导入任务");

        try {
            // 使用EasyExcel读取文件，指定DTO类型和监听器
            EasyExcel.read(inputStream, ExcelDictDTO.class, new ExcelDictDTOListener(baseMapper)).sheet().doRead();

            log.info("数据字典Excel导入任务成功完成");
        } catch (Exception e) {
            log.error("数据字典Excel导入失败", e);
            // 根据业务需求抛出特定异常
            throw new BusinessException(ResponseEnum.UPLOAD_ERROR, e);
        }
    }

    /**
     * Excel数据的导出
     */
    @Override
    public List<ExcelDictDTO> listDictData() {
        List<Dict> dictList = this.baseMapper.selectList(null);

        // 创建ExcelDictDTO列表，将Dict列表转换成ExcelDictDTO列表
        ArrayList<ExcelDictDTO> excelDictDTOList = new ArrayList<>(dictList.size());

        dictList.forEach(
                item -> {
                    ExcelDictDTO excelDictDTO = new ExcelDictDTO();
                    BeanUtils.copyProperties(item, excelDictDTO);
                    excelDictDTOList.add(excelDictDTO);
                }
        );
        return excelDictDTOList;
    }

    /**
     * 根据上级id获取子节点数据列表
     */
    @Override
    public List<Dict> listByParentId(Long parentId) {

        // 先查询redis中是否存在数据列表
        List<Dict> dictList = null;

        try {
            dictList = (List<Dict>) redisTemplate.opsForValue().get("srb:core:dictList:" + parentId);
            if (dictList != null) {
                log.info("从redis中取值");
                return dictList;
            }
        } catch (Exception e) {
            log.error("redis服务器异常:", e);
        }

        log.info("从数据库中取值");
        dictList = this.baseMapper.selectList(new LambdaQueryWrapper<Dict>().eq(Dict::getParentId, parentId));
        for (Dict dict : dictList) {
            // 如果有子节点，则是非叶子节点
            boolean hasChildren = this.hasChildren(dict.getId());
            dict.setHasChildren(hasChildren);
        }

        // 将数据存入redis
        try {
            redisTemplate.opsForValue().set("srb:core:dictList:" + parentId, dictList, 5, TimeUnit.MINUTES);
            log.info("数据存入redis");
        } catch (Exception e) {
            log.error("redis服务器异常：", e);
        }

        return dictList;
    }

    /**
     * 根据dictCode获取下级节点
     */
    @Override
    public List<Dict> findByDictCode(String dictCode) {
        LambdaQueryWrapper<Dict> wrapper = new LambdaQueryWrapper<Dict>().eq(Dict::getDictCode, dictCode);

        Dict dict = baseMapper.selectOne(wrapper);

        return this.listByParentId(dict.getId());
    }

    /**
     * 计算下拉列表选中内容
     */
    @Override
    public String getNameByParentDictCodeAndValue(String dictCode, Integer value) {
        // 防御性编程：处理参数为空的情况
        if (StringUtils.isEmpty(dictCode) || value == null) {
            return "";
        }

        // 查询父字典
        LambdaQueryWrapper<Dict> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Dict::getDictCode, dictCode)
                .orderByDesc(Dict::getValue);

        Dict parentDict = baseMapper.selectOne(wrapper);

        // 父字典不存在，直接返回空字符串
        if (parentDict == null) {
            return "";
        }

        // 查询子字典
        wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Dict::getParentId, parentDict.getId())
                .eq(Dict::getValue, value);

        Dict dict = this.baseMapper.selectOne(wrapper);

        // 使用三元表达式简化空值处理
        return dict != null ? dict.getName() : "";
    }

    /**
     * 判断该节点是否有子节点
     */
    private boolean hasChildren(Long id) {

        LambdaQueryWrapper<Dict> wrapper = new LambdaQueryWrapper<Dict>().eq(Dict::getParentId, id);

        Integer count = this.baseMapper.selectCount(wrapper);

        return count != null && count > 0;
    }
}
